/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.vrangogym.beans.utility;

import edu.chl.vrangogym.persistence.entities.User;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

/**
 * Used to upload an image file to be used as an avatar
 * 
 * @author Ulken
 */
@ManagedBean(name = "FileUpload")
@ApplicationScoped
public class FileUploadUtilityBean {

    private final String IMAGE_PATH = "//resources//images//avatars//";
    private final String DOT = "\\.";
    
    /** Creates a new instance of FileUploadUtilityBean */
    public FileUploadUtilityBean() {
    }

    public void handleFileUpload(FileUploadEvent event) {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        User user = (User) context.getSessionMap().get("Auth.user");
        UploadedFile uploadedFile = event.getFile();
        String extension = uploadedFile.getFileName().split(DOT)[1];
        String path = context.getRealPath(IMAGE_PATH + user.getUserName() + "." + extension);
        File imageFile = new File(path.toLowerCase());
        ImageIcon imageIcon = new ImageIcon(uploadedFile.getContents());
        Image image = imageIcon.getImage();
        RenderedImage rendered = null;
        if (image instanceof RenderedImage) {
            rendered = (RenderedImage) image;
        } else {
            BufferedImage buffered = new BufferedImage(
                    imageIcon.getIconWidth(),
                    imageIcon.getIconHeight(),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = buffered.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            rendered = buffered;
        }
        try {
            ImageIO.write(rendered, "Image", imageFile);
        } catch (IOException ex) {
            Logger.getLogger(FileUploadUtilityBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
